package com.sg.record.web;

import java.lang.reflect.InvocationTargetException;
import java.math.BigInteger;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.druid.sql.ast.SQLObject;
import com.alibaba.fastjson.JSONArray;
import com.sg.common.empty.core.ConditionRes;
import com.sg.common.empty.core.Conditions2;
import com.sg.common.empty.core.EpUtil;
import com.sg.common.empty.core.FilterVal;
import com.sg.common.empty.core.Params2;
import com.sg.common.empty.service.CfgService;
import com.sg.common.login.entity.Member;
import com.sg.common.login.service.OrgMemberService;
import com.sg.common.utils.CollUtil;
import com.sg.common.utils.Constant;
import com.sg.common.utils.DateTimeUtils;
import com.sg.common.utils.ReUtils;

@Repository
@Controller
@RequestMapping(value = "/api")
public class UmbrApiController {
	private Logger logger = Logger.getLogger(getClass());

	@Autowired
	CfgService service;
	
	@Autowired
	OrgMemberService omService;


	@RequestMapping(value = "/record/umbr/umbrList")
	@ResponseBody
	public Object findPlanList(HttpServletRequest request,
			@RequestBody Map<String, Object> requestBody) throws Exception {
		long s = System.currentTimeMillis();
		System.out.println("requestBody:    "+requestBody);
		
		String route = (String) request.getAttribute("conf.route");
		// TODO 如果有js，使用js确定使用哪个sql
		Conditions2 condis = Conditions2.init(request, requestBody);
//		HttpSession session = request.getSession();
//		List<String> myRoles = (List<String>) session
//				.getAttribute(Constant.SESSION_MYROLES_CODE);
//		Boolean canSeeAll = false;
//		if (CollUtil.isNotEmpty(myRoles)) {
//			for (String myRole : myRoles) {
//				String TRI001 = "TRI001";		//TRI001,企划部综合管理员与人教部教培科人员,可以看到所有部门中心培训计划/实际
//				if (StringUtils.equals(myRole, TRI001)) {
//					canSeeAll = true;
//					break;
//				}
//			}
//		}
//		if (canSeeAll) {
//			session.setAttribute(Constant.SESSION_MYDEPORG, null);
//		}

		ConditionRes cr = condis.buildCon();
		String sorts = condis.buildSorts();                                                                                                             
		String limit = condis.buildLimit();

		// 替换
		String orancsql = Constant.get(route + ".csql");
		String oransql = Constant.get(route + ".sql");
		orancsql = orancsql.replace("@conditions", cr.getSql()).replace(
				"@orderby", sorts);
		oransql = oransql.replace("@conditions", cr.getSql())
				.replace("@orderby", sorts).replace("@limit", limit);

		List<Object> countList = service.queryBySql(orancsql, cr.getParams());
		String res = Constant.get(route + ".res");
		List<Map<String, Object>> dataList = service.queryBySqlToMap(oransql,
				cr.getParams(), res.split(","));
		
		System.out.println(dataList);
		
//		List<Map<String, Object>> planList = new ArrayList<Map<String, Object>>();
		
//		System.out.println(planList);
		

		int count = ((BigInteger) countList.get(0)).intValue();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("items", dataList);
		map.put("total", count);
		map.put("code", 2000);
		long e = System.currentTimeMillis();
		System.out.println(e - s);
		return map;
	}
	
	
	@RequestMapping(value = "/record/umbr/add")
	@ResponseBody
	public Object addPlan(HttpServletRequest request,
			@RequestBody Map<String, Object> requestBody) throws Exception{
		String route = (String) request.getAttribute("conf.route");
		
//		ArrayList enable = (ArrayList)requestBody.get("enable");
		//盘点类型为日盘点时，需查找上一个班已完成交接班的日志,   查找相同班组下，已完成交接班的，且创建日期最近的日志   ①未找到，本站应有金额及站存金额直接赋值5000   ②找到后，本站应有金额及站存金额=上一个班的站存金额
		String type = requestBody.get("type").toString();
		if(type.equals("0")){
//			
			//找上一个班已完成交接班的日志,
			Conditions2 condis = Conditions2.init(request, requestBody);
			ConditionRes cr = condis.buildCon();
			String sorts = condis.buildSorts();
			String limit = condis.buildLimit();
//
//			// 替换
			String orantsql = Constant.get(route + ".tsql");
			orantsql = orantsql.replace("@conditions", cr.getSql()).replace("@orderby", sorts).replace("@limit", limit);
			
			String res = Constant.get(route + ".res");
			List<Map<String, Object>> tList = service.queryBySqlToMap(orantsql,cr.getParams(), res.split(","));
			System.out.println("tList:               "+tList);
			
			if(tList!=null && !tList.isEmpty()){
				//找到后，本站应有金额及站存金额=上一个班的站存金额
				requestBody.put("lumf", tList.get(0).get("tumf"));
				requestBody.put("lnum", tList.get(0).get("tnum"));
				requestBody.put("lfun", tList.get(0).get("tfun"));
			}else{
				//未找到，本站应有金额及站存金额直接赋值5000
				requestBody.put("lumf", 0); 
				requestBody.put("lnum", 0); 
				requestBody.put("lfun", 0); 
			}
//			
			String oransql = Constant.get(route + ".rsql");
			List<String> sqlParams = Params2.init(request,requestBody,service).build();
			service.excuteBySql(oransql, sqlParams.toArray());

			Map<String, Object> map = new HashMap<String, Object>();
			Map<String, Object> item = new HashMap<String, Object>();
			item.put("id", sqlParams.get(0));
			map.put("item", item);
			map.put("code", 2000);
			return map;
		}else{
			String oransql = Constant.get(route + ".ysql");
			List<String> ps = Constant.getStringList(route + ".yparams");
			List<String> sqlParams = Params2.init(request,requestBody,service).build(ps);
			service.excuteBySql(oransql, sqlParams.toArray());

			Map<String, Object> map = new HashMap<String, Object>();
			Map<String, Object> item = new HashMap<String, Object>();
			item.put("id", sqlParams.get(0));
			map.put("item", item);
			map.put("code", 2000);
			return map;
		}
	}
	
	
	@RequestMapping(value = "/record/umbr/update")
	@ResponseBody
	public Object up(HttpServletRequest request,@RequestBody Map<String, Object> requestBody) {
		String route = (String) request.getAttribute("conf.route");
		String oransql = Constant.get(route + ".sql");
		
		//计算本班结存雨伞数
		String lnum = requestBody.get("lnum").toString();		//上班结存雨伞数
		String inum = requestBody.get("inum").toString();		//本班调进雨伞数
		String gnum = requestBody.get("gnum").toString();		//本班归还完好雨伞数
		String dnum = requestBody.get("dnum").toString();		//本班归还破损雨伞数
		String lonu = requestBody.get("lonu").toString();		//本班借出雨伞数
		String onum = requestBody.get("onum").toString();		//本班调出雨伞数
		
		int tnum = calculateTnum(lnum, inum, gnum, dnum, lonu, onum);
		
		requestBody.put("tnum", tnum);
		
		//计算本班结存雨伞押金
		String lfun = requestBody.get("lfun").toString();		//上班结存雨伞备用金
		String lofu = requestBody.get("lofu").toString();		//本班借出雨伞押金
		String ifun = requestBody.get("ifun").toString();		//本班调进雨伞押金
		String gfun = requestBody.get("gfun").toString();		//本班归还完好雨伞雨伞押金
		String dfun = requestBody.get("dfun").toString();		//本班归还破损雨伞雨伞押金
		String ofun = requestBody.get("ofun").toString();		//本班调出雨伞押金
				
		int tfun = calculateTfun(lfun, lofu, ifun, gfun, dfun, ofun);
				
		requestBody.put("tfun", tfun);
		
		List<String> sqlParams = Params2.init(request,requestBody,service).build();
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			service.excuteBySql(oransql, sqlParams.toArray());
			map.put("code", 2000);
		} catch (Exception e) {
			logger.error(e.getMessage());
			map.put("code", 5030);
			map.put("msg", "更新发生内部错误，请联系管理员");
		}
		return map;
	}
	
	/**
	 * 便民雨伞本班结存雨伞数公式
	 * @param lnum + 上班结存雨伞数
	 * @param inum + 本班调进雨伞数
	 * @param gnum + 本班归还完好雨伞数
	 * @param dnum + 本班归还破损雨伞数
	 * @param lonu - 本班借出雨伞数
	 * @param onum - 本班调出雨伞数
	 * @return
	 */
	private int calculateTnum(String lnum, String inum, String gnum,
			String dnum, String lonu, String onum) {
		int sum = 0;
		if(StringUtils.isNotBlank(lnum)){
			sum += Integer.parseInt(lnum);
		}
		if(StringUtils.isNotBlank(inum)){
			sum += Integer.parseInt(inum);
		}
		if(StringUtils.isNotBlank(gnum)){
			sum += Integer.parseInt(gnum);
		}
		if(StringUtils.isNotBlank(dnum)){
			sum += Integer.parseInt(dnum);
		}
		if(StringUtils.isNotBlank(lonu)){
			sum -= Integer.parseInt(lonu);
		}
		if(StringUtils.isNotBlank(onum)){
			sum -= Integer.parseInt(onum);
		}
		return sum;
	}
	
	
	/**
	 * 便民雨伞本班结存雨伞押金计算公式
	 * @param lfun 上班结存雨伞押金	+
	 * @param lofu 本班借出雨伞押金 +
	 * @param ifun 本班调进雨伞押金 -
	 * @param gfun 本班归还完好雨伞雨伞押金 -
	 * @param dfun 本班归还破损雨伞雨伞押金 -
	 * @param ofun 本班调出雨伞押金 +
	 * @return
	 */
	private int calculateTfun(String lfun, String lofu, String ifun,
			String gfun, String dfun, String ofun) {
		int sum = 0;
		if(StringUtils.isNotBlank(lfun)){
			sum += Integer.parseInt(lfun);
		}
		if(StringUtils.isNotBlank(lofu)){
			sum += Integer.parseInt(lofu);
		}
		if(StringUtils.isNotBlank(ifun)){
			sum -= Integer.parseInt(ifun);
		}
		if(StringUtils.isNotBlank(gfun)){
			sum -= Integer.parseInt(gfun);
		}
		if(StringUtils.isNotBlank(dfun)){
			sum -= Integer.parseInt(dfun);
		}
		if(StringUtils.isNotBlank(ofun)){
			sum += Integer.parseInt(ofun);
		}
		return sum;
	}
	
	
	/**
	 * 便民雨伞，月度盘点时，区域站长手动清点确认
	 * @param request
	 * @return
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 * @throws NoSuchMethodException
	 */
	@RequestMapping(value = "/record/umbr/checkumbr", method = RequestMethod.POST)
	@ResponseBody
	public Object checkumbr(HttpServletRequest request,
			@RequestBody Map<String, Object> requestBody) throws Exception{
		String route = (String) request.getAttribute("conf.route");
		
		Map<String, Object> map = new HashMap<String, Object>();
		if(requestBody.get("enable").toString().equals("1")){
			if (StringUtils.equalsIgnoreCase(requestBody.get("createCode").toString(), requestBody.get("memCode").toString())) {//限定,日志创建人与账户登录人,必须为同一人！
				if (!StringUtils.equalsIgnoreCase(requestBody.get("confirmCode").toString(), requestBody.get("memCode").toString())) { // 接班时，必须接班人与当前登录账户不同(与日志创建账户不同)
					Member m = omService.confirmMember(requestBody.get("confirmCode").toString(),requestBody.get("confirmPass").toString());
					List<String> myRoles =  EpUtil.findRemoteRoles(request, requestBody.get("confirmCode").toString());
					if(m!=null){
						if(myRoles.indexOf("REC002") > -1 || myRoles.indexOf("REC001") > -1 || myRoles.indexOf("REC005") > -1){

							//得到接班人的id
							Conditions2 condis = Conditions2.init(request, requestBody);
							ConditionRes cr = condis.buildCon();
							String sorts = condis.buildSorts();
							String limit = condis.buildLimit();
							String idsql = Constant.get(route + ".idsql");
							idsql = idsql.replace("@conditions", cr.getSql()).replace("@orderby", sorts).replace("@limit", limit);
							
							List<Object> MemberId = service.queryBySql(idsql, cr.getParams());
							
							String confirmId = MemberId.get(0).toString();
							requestBody.put("confirmId", confirmId);
							
							String oransql = Constant.get(route + ".sql");
							List<String> sqlParams = Params2.init(request,requestBody,service).build();
							try {
								service.excuteBySql(oransql, sqlParams.toArray());
								map.put("code", 2000);
							} catch (Exception e) {
								logger.error(e.getMessage());
								map.put("code", 5030);
								map.put("msg", "更新发生内部错误，请联系管理员");
							}
							
						
						}else{
							map.put("code", 5000);
							map.put("msg", "该账号没有清点权限，请联系区域站长清点");
						}
					}else{
						map.put("code", 5000);
						map.put("msg", "该账号不存在");
					}
				}else{
					map.put("code", 5000);
					map.put("msg", "日志创建人与清点人不能为同一人，日志创建人工号："+requestBody.get("createCode").toString()+", 当前清点确定人工号："+requestBody.get("confirmCode").toString());
				}

			}else{
//				logger.error("");
				map.put("code", 5000);
				map.put("msg", "日志创建人与当前登录人必须为同一人，日志创建人工号："+requestBody.get("createCode").toString()+", 当前系统登录人工号："+requestBody.get("memCode").toString());
			}
			
		}else{
//			logger.error("");
			map.put("code", 5000);
			map.put("msg", "不能完成清点确认，请确认该应急备用金为新建状态");
			
		}
		return map;
	}

}
